package com.example.pucha_xian.Activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomControls;

import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.blankj.utilcode.util.StringUtils;
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment;
import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.SpatialReference;
import com.esri.arcgisruntime.layers.WebTiledLayer;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.Viewpoint;
import com.esri.arcgisruntime.mapping.view.Callout;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.IdentifyGraphicsOverlayResult;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol;
import com.example.pickerviewlibrary.picker.TeaPickerView;
import com.example.pickerviewlibrary.picker.entity.PickerData;
import com.example.pucha_xian.Adapter.ArcgisMapAdapter;
import com.example.pucha_xian.Class.CPoint;
import com.example.pucha_xian.Class.TianDiTuMethodsClass;
import com.example.pucha_xian.DemoApplication;
import com.example.pucha_xian.Dialog.BackPointsDialog;
import com.example.pucha_xian.R;
import com.example.pucha_xian.common.CoordinateBean;
import com.example.pucha_xian.common.OKHttp;
import com.example.pucha_xian.common.PointDTO;
import com.example.pucha_xian.common.PointVO;
import com.example.pucha_xian.common.PositionConvertUtil;
import com.example.pucha_xian.common.UserUtil;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.stream.Collectors;

import okhttp3.Call;
import okhttp3.Response;
import q.rorbin.badgeview.QBadgeView;

import static com.example.pucha_xian.Class.TianDiTuMethodsClass.CreateTianDiTuTiledLayer;

public class ArcgisActivity extends BaseActivity {
    private static final String TAG = "MainActivity";
    private static final int READ_CONTACTS_REQUEST = 1;
    private Context context;
    private MapView mapView;
    private ZoomControls m_zoom;
    private TextView tv_address;
    private TextView tv_status;
    private TextView tv_query;
    private TextView tv_query_count;
    private ImageView iv_location;
    private ImageView iv_message;
    private RecyclerView recyclerView;
    private List<PointDTO> pointDTOS = new ArrayList<>();
    private List<PointVO> backPointVOS = new ArrayList<>();
    private PointDTO pointDTO;
    private GraphicsOverlay graphicsoverlay;
    private Callout callout;
    //获取纬度信息
    double latitude;
    //获取经度信息
    double longitude;
    //获取纬度信息
    double latitude84;
    //获取经度信息
    double longitude84;
    private String token;
    private String username;
    private String country;
    private String city;
    private String status;
    private JsonObject jsData;
    private String jsonArray;
    private LocationClient myLocationClient;
    private BDLocationListener myListener = new MyLocationListener();
    private Boolean flag = true;
    private List<CPoint> cpoints;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = ArcgisActivity.this;

        // license with a license key
        ArcGISRuntimeEnvironment.setLicense("runtimestandard,1000,rud000572716,none,2KYRMD17JYEPDPF44120");//清除水印
        setContentView(R.layout.activity_arcgis);

        try {
            initView();
        } catch (Exception e) {

            flag = false;
        }

        if (flag) {
            initData();
            myLocationClient = new LocationClient(getApplication());
            initLocationOption();
            myLocationClient.registerLocationListener(myListener);
            myLocationClient.start();
        } else {
            Toast.makeText(this, "许可失效，请联系管理员。", Toast.LENGTH_LONG).show();
            Timer mTimer = new Timer();
            mTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    DemoApplication.getInstance().exit();
                }
            }, 3 * 1000);
        }

    }


    //控件初始化
    @SuppressLint("ClickableViewAccessibility")
    private void initView() {
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setAttributionTextVisible(false);//去除logo

        WebTiledLayer webTiledLayer = TianDiTuMethodsClass.CreateTianDiTuTiledLayer(TianDiTuMethodsClass.LayerType.TIANDITU_IMAGE_2000);
        Basemap tdtBasemap =new Basemap(webTiledLayer);//加载影像切片底图
        WebTiledLayer webTiledLayer1 = TianDiTuMethodsClass.CreateTianDiTuTiledLayer(TianDiTuMethodsClass.LayerType.TIANDITU_IMAGE_ANNOTATION_CHINESE_2000);
        tdtBasemap.getBaseLayers().add(webTiledLayer1);//叠加注记
        ArcGISMap basemap = new ArcGISMap(tdtBasemap);
        basemap.setInitialViewpoint(new Viewpoint(new Point(113.000275,28.061191, SpatialReference.create(4490)),20000));
        mapView.setMap(basemap);
        callout = mapView.getCallout();

        tv_address = findViewById(R.id.tv_address);
        tv_status = findViewById(R.id.tv_status);
        tv_query = findViewById(R.id.tv_query);
        tv_query_count = findViewById(R.id.tv_query_count);
        iv_location = findViewById(R.id.iv_location);
        iv_message=findViewById(R.id.iv_message);
        recyclerView = findViewById(R.id.item_recycleView);

        iv_message.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (backPointVOS.size()>0){
                    View view1=getLayoutInflater().inflate(R.layout.dialog_backpoints,null);
                    BackPointsDialog backPointsDialog=new BackPointsDialog(backPointVOS, ArcgisActivity.this,view1, R.style.DialogTheme);
                    backPointsDialog.setCancelable(true);
                    backPointsDialog.show();
                }

            }
        });
        SharedPreferences preferences = getSharedPreferences("PuCha", Context.MODE_PRIVATE);
        tv_address.setText(preferences.getString("country", null));
        tv_status.setText(preferences.getString("status", null));

        //刷新地图中心
        iv_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //刷新地图中心
                if (latitude != 0.0) {
                    if(callout.isShowing()){
                        callout.dismiss();
                    }
                    PositionConvertUtil positionConvertUtil = new PositionConvertUtil();
                    CoordinateBean coordinateBean = positionConvertUtil.gcj02ToWgs84(latitude, longitude);
                    Point point2D = new Point(coordinateBean.getLongitude(), coordinateBean.getLatitude(),SpatialReference.create(4490));
                    latitude84=coordinateBean.getLatitude();
                    longitude84=coordinateBean.getLongitude();
                    ImageView imageView = new ImageView(context);
                    imageView.setBackgroundResource(R.drawable.gps);
                    callout.show(imageView,point2D);
                    mapView.setViewpointCenterAsync(point2D);
                } else {
                    Toast.makeText(ArcgisActivity.this, "正在定位中。。。", Toast.LENGTH_LONG).show();
                }
            }
        });
        //状态选择器
        PickerData data = new PickerData();

        List<String> statuslist = new ArrayList<>(Arrays.asList("已下发", "已提交", "初审完成","初审驳回", "终审完成","终审驳回","全状态"));
        data.setFirstDatas(statuslist);
        data.setInitSelectText("选择状态");
        TeaPickerView teaPickerView = new TeaPickerView(this, data);
        teaPickerView.setScreenH(3)
                .setDiscolourHook(true)
                .setRadius(25)
                .setContentLine(true)
                .setRadius(25)
                .build();
        tv_status.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                teaPickerView.show(tv_status);
            }
        });
        //选择器点击事件
        teaPickerView.setOnPickerClickListener(pickerData -> {
            Toast.makeText(ArcgisActivity.this, pickerData.getFirstText(), Toast.LENGTH_SHORT).show();
            tv_status.setText(pickerData.getFirstText());
            teaPickerView.dismiss();//关闭选择器
        });

        //地址选择器
        PickerData dataAddress = new PickerData();

        List<String> cities = new ArrayList<>(Arrays.asList("娄底市", "岳阳市", "常德市", "张家界市", "怀化市", "株洲市", "永州市", "湘潭市", "湘西土家族苗族自治州"
                , "益阳市", "衡阳市", "邵阳市", "郴州市", "长沙市", "全省"));

        dataAddress.setFirstDatas(cities);
        Map<String, List<String>> coutries = new HashMap<>();
        coutries.put("娄底市", new ArrayList<>(Arrays.asList("娄底市", "冷水江市", "双峰县", "娄星区", "新化县", "涟源市")));
        coutries.put("岳阳市", new ArrayList<>(Arrays.asList("岳阳市", "临湘市", "云溪区", "华容县", "君山区", "岳阳县", "岳阳楼区", "平江县", "汨罗市", "湘阴县")));
        coutries.put("常德市", new ArrayList<>(Arrays.asList("常德市", "临澧县", "安乡县", "桃源县", "武陵区", "汉寿县", "津市市", "澧县", "石门县", "鼎城区")));
        coutries.put("张家界市", new ArrayList<>(Arrays.asList("张家界市", "慈利县", "桑植县", "武陵源区", "永定区")));
        coutries.put("怀化市", new ArrayList<>(Arrays.asList("怀化市", "中方县", "会同县", "新晃侗族自治县", "沅陵县", "洪江市", "溆浦县", "芷江侗族自治县", "辰溪县", "通道侗族自治县", "靖州苗族侗族自治县", "鹤城区", "麻阳苗族自治县")));
        coutries.put("株洲市", new ArrayList<>(Arrays.asList("株洲市", "天元区", "攸县", "渌口区", "炎陵县", "石峰区", "芦淞区", "茶陵县", "荷塘区", "醴陵市")));
        coutries.put("永州市", new ArrayList<>(Arrays.asList("永州市", "东安县", "冷水滩区", "双牌县", "宁远县", "新田县", "江华瑶族自治县", "江永县", "祁阳县", "蓝山县", "道县", "零陵区")));
        coutries.put("湘潭市", new ArrayList<>(Arrays.asList("湘潭市","岳塘区", "湘乡市", "湘潭县", "雨湖区", "韶山市")));
        coutries.put("湘西土家族苗族自治州", new ArrayList<>(Arrays.asList("湘西土家族苗族自治州", "保靖县", "凤凰县", "古丈县", "吉首市", "永顺县", "泸溪县", "花垣县", "龙山县")));
        coutries.put("益阳市", new ArrayList<>(Arrays.asList("益阳市", "南县", "安化县", "桃江县", "沅江市", "资阳区", "赫山区")));
        coutries.put("衡阳市", new ArrayList<>(Arrays.asList("衡阳市", "南岳区", "常宁市", "珠晖区", "石鼓区", "祁东县", "耒阳市", "蒸湘区", "衡东县", "衡南县", "衡山县", "衡阳县", "雁峰区")));
        coutries.put("邵阳市", new ArrayList<>(Arrays.asList("邵阳市", "北塔区", "双清区", "城步苗族自治县", "大祥区", "新宁县", "新邵县", "武冈市", "洞口县", "绥宁县", "邵东县", "邵阳县", "隆回县")));
        coutries.put("郴州市", new ArrayList<>(Arrays.asList("郴州市", "临武县", "北湖区", "嘉禾县", "安仁县", "宜章县", "桂东县", "桂阳县", "永兴县", "汝城县", "苏仙区", "资兴市")));
        coutries.put("长沙市", new ArrayList<>(Arrays.asList("长沙市", "天心区", "宁乡市", "岳麓区", "开福区", "望城区", "浏阳市", "芙蓉区", "长沙县", "雨花区")));
        coutries.put("全省", new ArrayList<>(Arrays.asList("全省")));
        dataAddress.setSecondDatas(coutries);
        dataAddress.setInitSelectText("选择地址");

        TeaPickerView teaPickerView2 = new TeaPickerView(this, dataAddress);
        teaPickerView2.setScreenH(3)
                .setDiscolourHook(true)
                .setRadius(25)
                .setContentLine(true)
                .setRadius(25)
                .build();
        tv_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                teaPickerView2.show(tv_address);
            }
        });
        //选择器点击事件
        teaPickerView2.setOnPickerClickListener(pickerData -> {
            Toast.makeText(ArcgisActivity.this, pickerData.getSecondText(), Toast.LENGTH_SHORT).show();
            tv_address.setText(pickerData.getSecondText());
            city = pickerData.getFirstText();
            country = pickerData.getSecondText();
            teaPickerView2.dismiss();//关闭选择器
        });

        //查询
        tv_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences preferences = getSharedPreferences("PuCha", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = preferences.edit();
                if (!StringUtils.isEmpty(tv_address.getText())) {
                    editor.putString("country", tv_address.getText().toString());
                }
                if (!StringUtils.isEmpty(tv_status.getText())) {
                    editor.putString("status", tv_status.getText().toString());
                }
                editor.apply();
                pointDTOS = new ArrayList<>();
                backPointVOS=new ArrayList<>();
                initData();

            }
        });
    }

    private void initData() {
        List<String> cities = new ArrayList<>(Arrays.asList("娄底市", "岳阳市", "常德市", "张家界市", "怀化市", "株洲市", "永州市", "湘潭市", "湘西土家族苗族自治州"
                , "益阳市", "衡阳市", "邵阳市", "郴州市", "长沙市"));
        final String jsonData;
        SharedPreferences preferences = getSharedPreferences("PuCha", Context.MODE_PRIVATE);
        token = preferences.getString("token", null);
        username = preferences.getString("username", null);
        country = tv_address.getText().toString();
        if (!"全状态".equals(tv_status.getText().toString())) {
            status = tv_status.getText().toString();
        } else {
            status = null;
        }
        if (!"全省".equals(tv_address.getText().toString())) {
            country = tv_address.getText().toString();
        } else {
            country = null;
            city = null;
        }
        if (!StringUtils.isEmpty(city)){
            if (city.equals(country)){
                country=null;
            }
        }
        if (!StringUtils.isEmpty(tv_address.getText().toString())){
            if (cities.contains(tv_address.getText().toString())){
                city=tv_address.getText().toString();
                country=null;
            }
        }


        if (graphicsoverlay != null) {
            graphicsoverlay.getGraphics().clear();
        }
        graphicsoverlay = new GraphicsOverlay(GraphicsOverlay.RenderingMode.DYNAMIC);
        OKHttp.postData(UserUtil.showPoint, token, username, city,country, status, new okhttp3.Callback() {
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                //请求成功返回结果 ，如果希望返回的是字符串
                final String responseData = response.body().string();

                // 注意，此时的线程不是ui线程，
                // 如果此时我们要用返回的数据进行ui更新，操作控件，就要使用相关方法
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // 更新UI的操作
                        Message message = new Message();
                        message.obj = responseData;
                        message.arg1 = 1;
                        handler.sendMessage(message);
                    }
                }).start();
            }

            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e("post 请求失败", "======e.getMessage()" + e.getMessage());
                Looper.prepare();
                Toast.makeText(ArcgisActivity.this, "网络出问题了!", Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        });

        OKHttp.postBackPoints(UserUtil.showBackPoint, token, username, "初审驳回", new okhttp3.Callback() {
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                //请求成功返回结果 ，如果希望返回的是字符串
                final String responseData = response.body().string();

                // 注意，此时的线程不是ui线程，
                // 如果此时我们要用返回的数据进行ui更新，操作控件，就要使用相关方法
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // 更新UI的操作
                        Message message = new Message();
                        message.obj = responseData;
                        message.arg1 = 2;
                        handler.sendMessage(message);
                    }
                }).start();
            }

            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e("post 请求失败", "======e.getMessage()" + e.getMessage());
                Looper.prepare();
                Toast.makeText(ArcgisActivity.this, "网络出问题了!", Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        });

        mapView.getGraphicsOverlays().add(graphicsoverlay);
        // mapControl.getMap().setScale(0.0001);
        recyclerView.setVisibility(View.VISIBLE);
        recyclerView.setLayoutManager(new LinearLayoutManager(ArcgisActivity.this));
        recyclerView.addItemDecoration(new DividerItemDecoration(ArcgisActivity.this, DividerItemDecoration.VERTICAL));
        recyclerView.setAdapter(new ArcgisMapAdapter(pointDTOS, recyclerView, mapView));
        listen();

    }

    @SuppressLint("ClickableViewAccessibility")
    private void listen() {
        // 屏幕点击事件
        mapView.setOnTouchListener(new DefaultMapViewOnTouchListener(context, mapView) {

            //单击屏幕时触发
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                if (callout.isShowing()) {
                    callout.dismiss();
                }
                graphicsoverlay.clearSelection();
                //获取屏幕点坐标
                android.graphics.Point screenPoint = new android.graphics.Point(Math.round(e.getX()), Math.round(e.getY()));
                ListenableFuture<IdentifyGraphicsOverlayResult> identifyGraphics = mapView.identifyGraphicsOverlayAsync(graphicsoverlay,screenPoint,20,false,1);

                // add done loading listener to fire when the selection returns
                identifyGraphics.addDoneListener(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            // call get on the future to get the result
                            IdentifyGraphicsOverlayResult grapchicResult = identifyGraphics.get();
                            List<Graphic> resultGraElements = grapchicResult.getGraphics();
                            if (!resultGraElements.isEmpty()) {
                                if (resultGraElements.get(0) != null) {
                                    Graphic graphic = (Graphic) resultGraElements.get(0);
                                    Point p = (Point) graphic.getGeometry();
                                    Intent intent = new Intent(context, WorkActivity.class);
                                    List<CPoint> result = cpoints.stream().filter(b -> b.getLng().equals(p.getX()) && b.getLat().equals(p.getY())).collect(Collectors.toList());
                                    if (result.size() == 0) {
                                        Toast toast = Toast.makeText(ArcgisActivity.this, "数据库查不到数据！", Toast.LENGTH_LONG);
                                        toast.show();
                                    } else {
                                        CPoint Point1 = result.get(0);
                                        intent.putExtra("cpoint", Point1);
                                        intent.putExtra("lat",latitude84);
                                        intent.putExtra("lng",longitude84);
                                        startActivity(intent);
                                    }
                                }
                            } else {
                                // none of the features on the map were selected
                                callout.dismiss();
                            }
                        } catch (Exception e) {
                            Log.e(TAG, "Select feature failed: " + e.getMessage());
                        }
                    }
                });
                return super.onSingleTapConfirmed(e);
            }
        });
    }

    @SuppressLint("HandlerLeak")
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(@NotNull Message msg) {
            Point point2D;
            Graphic graphic;
            PictureMarkerSymbol symbol;
            BitmapDrawable bitmapGPS = (BitmapDrawable) getResources().getDrawable(R.drawable.gnss);
            BitmapDrawable bitmapHNCORS = (BitmapDrawable) getResources().getDrawable(R.drawable.hncors);
            BitmapDrawable bitmapSANJIAO = (BitmapDrawable) getResources().getDrawable(R.drawable.sanjiao);
            BitmapDrawable bitmapBenchmark = (BitmapDrawable) getResources().getDrawable(R.drawable.benchmark);
            BitmapDrawable bitmapGPS1 = (BitmapDrawable) getResources().getDrawable(R.drawable.gnss1);
            BitmapDrawable bitmapHNCORS1 = (BitmapDrawable) getResources().getDrawable(R.drawable.hncors1);
            BitmapDrawable bitmapSANJIAO1 = (BitmapDrawable) getResources().getDrawable(R.drawable.sanjiao1);
            BitmapDrawable bitmapBenchmark1 = (BitmapDrawable) getResources().getDrawable(R.drawable.benchmark1);
            //BitmapDrawable bitmapFLAG = (BitmapDrawable) getResources().getDrawable(R.drawable.flag);
            super.handleMessage(msg);
            try {
                jsData = new JsonParser().parse(msg.obj.toString()).getAsJsonObject();
                if (jsData.get("status") != null) {
                    if (jsData.get("status").toString().equals("500")) {
                        Toast.makeText(ArcgisActivity.this, "登录已过期,请重新登录", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(ArcgisActivity.this, LoginActivity.class);
                        startActivity(intent);
                        ArcgisActivity.this.finish();
                    }
                }
                jsonArray = String.valueOf(jsData.get("data"));
                if (jsonArray != null) {
                    Log.e("AAAA",""+msg);
                    Log.e("BBBB",""+jsonArray);
                    if (msg.arg1 == 1) {
                        Type type1 = new TypeToken<List<CPoint>>() {
                        }.getType();
                        cpoints = new Gson().fromJson(jsonArray, type1);
                        for (CPoint cpoint : cpoints) {
                            point2D = new Point(cpoint.getLng(), cpoint.getLat());
                            graphic = new Graphic();
                            graphic.setGeometry(point2D);
                            if (!StringUtils.isEmpty(cpoint.getUploadpanorama()) && !StringUtils.isEmpty(cpoint.getUploadcloseup()) && !StringUtils.isEmpty(cpoint.getUploadbust())&&!cpoint.getStatus().equals("初审驳回")&&!cpoint.getStatus().equals("终审驳回")) {
                                if("三角点".equals(cpoint.getBzlb())){
                                    symbol = new PictureMarkerSymbol(bitmapSANJIAO1);
                                }else if("基站点".equals(cpoint.getBzlb())){
                                    symbol = new PictureMarkerSymbol(bitmapHNCORS1);
                                }else if("GPS点".equals(cpoint.getBzlb())){
                                    symbol = new PictureMarkerSymbol(bitmapGPS1);
                                }else {
                                    symbol = new PictureMarkerSymbol(bitmapBenchmark1);
                                }
                            } else if ("三角点".equals(cpoint.getBzlb())) {
                                symbol = new PictureMarkerSymbol(bitmapSANJIAO);
                            } else if ("基站点".equals(cpoint.getBzlb())) {
                                symbol = new PictureMarkerSymbol(bitmapHNCORS);
                            } else if ("GPS点".equals(cpoint.getBzlb())) {
                                symbol = new PictureMarkerSymbol(bitmapGPS);
                            } else {
                                symbol = new PictureMarkerSymbol(bitmapBenchmark);
                            }
                            symbol.setHeight(20);
                            symbol.setWidth(20);
                            graphic.setSymbol(symbol);
                            graphicsoverlay.getGraphics().add(graphic);
                            pointDTO = new PointDTO(cpoint.getName(), cpoint.getPointID(), cpoint.getStatus(), cpoint.getLng(), cpoint.getLat());
                            pointDTOS.add(pointDTO);
                            // mapControl.getMap().setCenter(point2D);
                        }
                    }else if (msg.arg1 == 2){
                        Type type3 = new TypeToken<List<PointVO>>() {}.getType();
                        List<PointVO> pointVOS = new Gson().fromJson(jsonArray, type3);
                        backPointVOS.addAll(pointVOS);
                    }
                }
                tv_query_count.setText("数量：" + pointDTOS.size());
                new QBadgeView(context).bindTarget(iv_message).setBadgeNumber(backPointVOS.size()).setBadgeGravity(Gravity.END | Gravity.TOP)
                        .setGravityOffset(10,5,true);
            } catch (Exception e) {
                Toast.makeText(ArcgisActivity.this, "登录已过期,请重新登录", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(ArcgisActivity.this, LoginActivity.class);
                startActivity(intent);
                ArcgisActivity.this.finish();
            }
        }
    };



    /**
     * 初始化定位参数配置
     */

    private void initLocationOption() {
        //定位服务的客户端。宿主程序在客户端声明此类，并调用，目前只支持在主线程中启动
        LocationClient locationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类实例并配置定位参数
        LocationClientOption locationOption = new LocationClientOption();
        MyLocationListener myLocationListener = new MyLocationListener();
        //注册监听函数
        locationClient.registerLocationListener(myLocationListener);
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        locationOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认gcj02，设置返回的定位结果坐标系，如果配合百度地图使用，建议设置为bd09ll;
        locationOption.setCoorType("gcj02");
        //可选，默认0，即仅定位一次，设置发起连续定位请求的间隔需要大于等于1000ms才是有效的,设置发起定位请求的间隔时间为36秒
        locationOption.setScanSpan(15 * 1000);
        //可选，设置是否需要地址信息，默认不需要
        locationOption.setIsNeedAddress(true);
        //可选，设置是否需要地址描述
        locationOption.setIsNeedLocationDescribe(true);
        //可选，设置是否需要设备方向结果
        locationOption.setNeedDeviceDirect(false);
        //可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        locationOption.setLocationNotify(true);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        locationOption.setIgnoreKillProcess(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        locationOption.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        locationOption.setIsNeedLocationPoiList(true);
        //可选，默认false，设置是否收集CRASH信息，默认收集
        locationOption.SetIgnoreCacheException(false);
        //可选，默认false，设置是否开启Gps定位
        locationOption.setOpenGps(true);
        //可选，默认false，设置定位时是否需要海拔信息，默认不需要，除基础定位版本都可用
        locationOption.setIsNeedAltitude(false);
        //设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者，该模式下开发者无需再关心定位间隔是多少，定位SDK本身发现位置变化就会及时回调给开发者
        //locationOption.setOpenAutoNotifyMode();
        //设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者
        //locationOption.setOpenAutoNotifyMode(3000, 1, LocationClientOption.LOC_SENSITIVITY_HIGHT);
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        locationClient.setLocOption(locationOption);
        //开始定位
        locationClient.start();
    }


    /**
     * 实现定位回调
     */

    public class MyLocationListener implements BDLocationListener {
        private static final String TAG = "Location";

        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明

            //获取纬度信息
            latitude = location.getLatitude();
            //获取经度信息
            longitude = location.getLongitude();
            //获取定位精度，默认值为0.0f
            float radius = location.getRadius();
            //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准
            String coorType = location.getCoorType();
            //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
            int errorCode = location.getLocType();

//            Log.e(TAG, "onReceiveLocation: "+latitude+","+longitude +"时间："+new Date().toString());
//            Log.e(TAG,"locationType:"+location.getLocType());
            //刷新地图中心
            if (latitude != 0.0) {
                if(callout.isShowing()){
                    callout.dismiss();
                }
                PositionConvertUtil positionConvertUtil = new PositionConvertUtil();
                CoordinateBean coordinateBean = positionConvertUtil.gcj02ToWgs84(latitude, longitude);
                Point point2D = new Point(coordinateBean.getLongitude(), coordinateBean.getLatitude(), SpatialReference.create(4490));
                latitude84=coordinateBean.getLatitude();
                longitude84=coordinateBean.getLongitude();
                ImageView imageView = new ImageView(context);
                imageView.setBackgroundResource(R.drawable.gps);
                callout.show(imageView,point2D);
                mapView.setViewpointCenterAsync(point2D,20000);
            }
        }
    }

    /**
     *  MapView的生命周期与Activity同步，当activity挂起时需调用MapView.pause()
     */
    @Override
    protected void onPause() {
        mapView.pause();
        super.onPause();
    }

    /**
     *  MapView的生命周期与Activity同步，当activity恢复时需调用MapView.resume()
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.resume();
    }

    /**
     *  MapView的生命周期与Activity同步，当activity销毁时需调用MapView.dispose()
     */
    @Override
    protected void onDestroy() {
        mapView.dispose();
        super.onDestroy();
    }
}
